<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="uname" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number"  v-model.number="year"/>
    </div>
    <div>
      <span>性别:</span>
      <select v-model="sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="addFn">添加/修改</button>
    </div>
    <div>
      <table
        border="1"
        cellpadding="10"
        cellspacing="0"
      >
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in arr" :key="index">
          <td> {{index + 1}}</td>
          <td>{{ item.name}}</td>
          <td>{{item.age}}</td>
          <td>{{item.gender}}</td>
          <td>
            <button @click="delFn(item.id)">删除</button>
            <button @click="xgBtn(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
    data() {
       return {
          arr: [
             {  
                id: +new Date(), 
                name: 'Tom',
                age: 19,
                gender:'男'

              },
              {
                id: +new Date(), 
                name: 'Jone',
                age: 21,
                gender:'女'
              },
          ],
          uname: '',   // 名字
          year: '',    // 年龄
          sex: '',     // 性别
       }
    },
    methods: {
      // 新增
       addFn(){
          // 判断是否有内容
          if(this.uname.trim().length === 0 || this.year <= 0){
                return alert('请输入学生信息')
          }

          this.arr.push({
                id: +new Date(), 
                name: this.uname,
                age: this.year,
                gender: this.sex
          })
       },
      //  删除
      delFn(id) {
           this.arr = this.arr.filter(item => item.id !== id)
      },

      // 修改数据回显   有问题
      xgBtn(ind) {
        // 传入 id 写法
        //  const res = this.arr.filter(item => item.id === id)
        //  this.uname = res.uname
        //  this.year = res.year
        // console.log(res);

        
        // 传入索引写法
        // this.uname = this.arr[ind].uname
        // this.gender = this.arr[ind].gender
        // this.sex = this.arr[ind].sex

      }
    }
}
</script>
